package com.observatory.baapp;

import static android.content.Context.MODE_PRIVATE;
import static android.content.Context.NOTIFICATION_SERVICE;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import java.io.IOException;

import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class MyJPushMessageReceiver extends JPushMessageReceiver {
    @Override
    public void onRegister(Context context, String registrationId) {
        super.onRegister(context, registrationId);
        Log.w("JPushDebug", "--- Registration Received ---");
        Log.w("JPushDebug", "RegID: " + registrationId);
        // 上传 Token 到服务器
//        sendJPushTokenToServer(registrationId);
//        // 额外保存到本地
//        SharedPreferences prefs = context.getSharedPreferences("jpush", MODE_PRIVATE);
//        prefs.edit().putString("registrationId", registrationId).apply();
    }

    public void onMessage(Context context, CustomMessage customMessage) {
        if (!isUserLoggedIn(context)) {
            Log.d("JPush", "用户未登录，忽略通知");
            return;
        }
        super.onMessage(context, customMessage);
        Log.d("JPush", "收到自定义消息: " + customMessage.message);

        if (isAppInBackground(context)) {
            sendSystemNotificationForCustomMessage(context, customMessage);
        } else {
            showDialogForCustomMessage(context, customMessage);
        }
        // 触发 EventList 刷新
        triggerEventListRefresh(context);
    }

    private void sendSystemNotificationForCustomMessage(Context context, CustomMessage customMessage) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        // 创建通知渠道（兼容 Android O 及以上）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "developer-default",
                    "JPUSH_CHANNEL",
                    NotificationManager.IMPORTANCE_HIGH
            );
            notificationManager.createNotificationChannel(channel);
        }

        // 构建通知
        String channelId = "developer-default";
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle("New Message")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentText(customMessage.message)
                .setContentIntent(getPendingIntent(context))
                .setAutoCancel(true);

        Notification notification = builder.build();

        // 显示通知
        notificationManager.notify(1, notification);
    }

    private void showDialogForCustomMessage(Context context, CustomMessage customMessage) {
        Intent intent = new Intent(context, NotificationDialogActivity.class);
        intent.putExtra("title", "New Message");
        intent.putExtra("message", customMessage.message);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    //  getPendingIntent 方法
    private PendingIntent getPendingIntent(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return PendingIntent.getActivity(
                context,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
    }

    private boolean isAppInBackground(Context context) {
        MyApp app = (MyApp) context.getApplicationContext();
        return !app.isAppInForeground();
    }

    // 检查用户是否登录
    private boolean isUserLoggedIn(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("CapacitorStorage", Context.MODE_PRIVATE);
        return "true".equals(prefs.getString("isLoggedIn", "false"));
    }

    @Override
    public void onNotifyMessageArrived(Context context, NotificationMessage message) {
        if (!isUserLoggedIn(context)) {
            cancelNotification(context, message.notificationId);
            return;
        }

        if (isAppInBackground(context)) {
            sendSystemNotification(context, message);
        } else {
            showDialog(context, message);
            cancelNotification(context, message.notificationId);
        }
        // 触发 EventList 刷新
        triggerEventListRefresh(context);
    }

    private void sendSystemNotification(Context context, NotificationMessage message) {
        NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        // 创建通知渠道（兼容Android O+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "developer-default",
                    "JPUSH_CHANNEL",
                    NotificationManager.IMPORTANCE_HIGH
            );
            manager.createNotificationChannel(channel);
        }

        // 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "developer-default")
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle(message.notificationTitle)
                .setContentText(message.notificationContent)
                .setContentIntent(getPendingIntent(context))
                .setAutoCancel(true);

        manager.notify(message.notificationId, builder.build());
    }

    private void showDialog(Context context, NotificationMessage message) {
        Intent intent = new Intent(context, NotificationDialogActivity.class);
        intent.putExtra("title", message.notificationTitle);
        intent.putExtra("message", message.notificationContent);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public void onNotifyMessageOpened(Context context, NotificationMessage message) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        super.onNotifyMessageOpened(context, message);
    }

    // 取消指定ID的通知
    private void cancelNotification(Context context, int notificationId) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.cancel(notificationId);
        }
    }

    private void triggerEventListRefresh(Context context) {
        Log.d("JPushDebug", "通过事件总线触发 EventList 刷新");
        EventBus.getInstance().post("refreshEventList");
    }
}
